/******************************************************************************/
/********************************** 功能方法 **********************************/
/******************************************************************************/

import { CommonObj } from "@/types";

/**
 * 获取带错别字，敏感词标识的html字符串
 * @param {string} str 要处理的字符串
 * @param {string[]} wrongWords 错别字数组
 * @param {string[]} sensWords 敏感词数组
 * @param {string} wrongStyle 错别字样式
 * @param {string} sensStyle 敏感词样式
 * @example getTagHtmlStr("我们的假象，在希望的田野上，热爱我们的祖国！",['假象'],['我', '的'])
 */
export function getTagHtmlStr(
  str = "",
  wrongWords: string[] = [],
  sensWords: string[] = [],
  wrongStyle = "color: red;",
  sensStyle = "color: darkorange;"
) {
  // wrongGroups=['假象->家乡']
  // const wrongWords = wrongGroups.map(it=>it.split("->")[0])
  const wrongStr = wrongWords.join("|");
  const sensStr = sensWords.join("|");
  const wordStr = [wrongStr, sensStr]
    .filter((it) => it !== "")
    .map((item) => (item ? `(${item})` : item))
    .join("|");
  if (str && wordStr) {
    const reg = new RegExp(wordStr, "g");
    str = str.replace(reg, (matchStr: string) => {
      const isWrong = wrongWords.includes(matchStr);
      return `<span style="${
        isWrong ? wrongStyle : sensStyle
      }">${matchStr}</span>`;
    });
  }
  return str;
}

/**
 * 获取html文本
 * @param {string} str 要高亮的文本
 * @param {string} words 关键词
 * @param {string} style 高亮的样式
 * @returns {string} html字符串
 */
export const getHtmlStr = (
  str: string,
  words: string,
  style = "color:red"
): string => {
  const index = str.indexOf(words);
  const beforeStr = str.substring(0, index);
  const afterStr = str.slice(index + words.length);
  if (index > -1)
    return `<span>${beforeStr}<span style="${style}">${words}</span>${afterStr}</span>`;
  return `<span>${str}</span>`;
};

/**
 * 根据关键词模糊过滤树节点
 * @param {string} val 模糊搜索的关键词
 * @param {CommonObj[]} tree 树数据
 * @param {CommonObj[]} newArr 缓存的节点树
 * @returns {CommonObj[]} 返回一个新的树，不改变原数组
 */
export const filterTreeByKeywords = (
  val: string,
  tree: CommonObj[],
  newArr: CommonObj[] = []
): CommonObj[] => {
  if (!(tree.length && val)) return tree;
  tree.forEach((item) => {
    const { title, children } = item;
    if (title.includes(val)) {
      item.title = getHtmlStr(title, val);
      if (children?.length) {
        item.children = filterTreeByKeywords(val, children);
      }
      return newArr.push(item);
    }
    if (!children?.length) return item;
    const subArr = filterTreeByKeywords(val, children);
    if (subArr?.length) {
      item.title = getHtmlStr(title, val);
      newArr.push({ ...item, children: subArr });
    }
    return item;
  });
  return newArr;
};
